//
//  ImproveResumeTC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/8/4.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class ImproveResumeTC: UITableViewController, UICollectionViewDelegate, UICollectionViewDataSource ,
    MTImagePickerControllerDelegate, FactoryCollCellDelegate {
    
    private var dataSource = [MTImagePickerModel]()//照片的数据源

    @IBOutlet weak var companyName: UITextField!
    @IBOutlet weak var positionName: UITextField!
    @IBOutlet weak var startTime: UILabel!
    @IBOutlet weak var startTimePlace: UILabel!
    @IBOutlet weak var endTime: UILabel!
    @IBOutlet weak var endTimePlace: UILabel!
    @IBOutlet weak var addBtn: UIButton!
    @IBOutlet weak var nextLight: UITextField!
    @IBOutlet weak var light1: UIButton!
    @IBOutlet weak var light2: UIButton!
    @IBOutlet weak var light3: UIButton!
    @IBOutlet weak var light4: UIButton!
    @IBOutlet weak var light5: UIButton!
    @IBOutlet weak var light6: UIButton!
    @IBOutlet weak var light7: UIButton!
    @IBOutlet weak var light8: UIButton!
    @IBOutlet weak var light9: UIButton!
    @IBOutlet weak var light10: UIButton!
    @IBOutlet weak var light11: UIButton!
    @IBOutlet weak var light12: UIButton!
    @IBOutlet weak var nextBtn: UIButton!
    
    @IBOutlet weak var collection: UICollectionView!
    
    @IBOutlet weak var photoBtn: UIButton!
    var id: String?
    //var clickedCount = 0//按钮的点击次数
    var imgsrc: UIImage?
    var collectionArr: [UIImage] = []//形象展示的数组

    var collectionStrArr: [String] = []//存放图片文件
    var lightArray:[String] = [ ]//存放亮点的数组
    var nilArr: [UIImage] = []
    let footerView = PerfectResumeFooter.create()
    var msg: regiestInfo?
    
    var deleteBtnFlag:Bool!
    var rotateAniFlag:Bool!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.tableView.tableFooterView = footerView

        footerView.completeBtn.addTarget(self, action: #selector(ImproveResumeTC.publishBtn), forControlEvents: UIControlEvents.TouchUpInside)
        self.collection.hidden = true
        self.collection.scrollEnabled = false
        let cellNib = UINib(nibName: "FactoryCollCell", bundle: nil)
        
        self.collection.registerNib(cellNib, forCellWithReuseIdentifier: "FactoryCollCell")
        
        deleteBtnFlag = true
        rotateAniFlag = true
        
        self.light1.layer.masksToBounds = true
        self.light1.layer.borderWidth = 1
        self.light1.layer.borderColor = BODER_COLOR.CGColor
        self.light2.layer.masksToBounds = true
        self.light2.layer.borderWidth = 1
        self.light2.layer.borderColor = BODER_COLOR.CGColor
        self.light3.layer.masksToBounds = true
        self.light3.layer.borderWidth = 1
        self.light3.layer.borderColor = BODER_COLOR.CGColor
        self.light4.layer.masksToBounds = true
        self.light4.layer.borderWidth = 1
        self.light4.layer.borderColor = BODER_COLOR.CGColor
        self.light5.layer.masksToBounds = true
        self.light5.layer.borderWidth = 1
        self.light5.layer.borderColor = BODER_COLOR.CGColor
        self.light6.layer.masksToBounds = true
        self.light6.layer.borderWidth = 1
        self.light6.layer.borderColor = BODER_COLOR.CGColor
        self.light7.layer.masksToBounds = true
        self.light7.layer.borderWidth = 1
        self.light7.layer.borderColor = BODER_COLOR.CGColor
        self.light8.layer.masksToBounds = true
        self.light8.layer.borderWidth = 1
        self.light8.layer.borderColor = BODER_COLOR.CGColor
        self.light9.layer.masksToBounds = true
        self.light9.layer.borderWidth = 1
        self.light9.layer.borderColor = BODER_COLOR.CGColor
        self.light10.layer.masksToBounds = true
        self.light10.layer.borderWidth = 1
        self.light10.layer.borderColor = BODER_COLOR.CGColor
        self.light11.layer.masksToBounds = true
        self.light11.layer.borderWidth = 1
        self.light11.layer.borderColor = BODER_COLOR.CGColor
        self.light12.layer.masksToBounds = true
        self.light12.layer.borderWidth = 1
        self.light12.layer.borderColor = BODER_COLOR.CGColor
        self.nextBtn.layer.masksToBounds = true
        self.nextBtn.layer.borderWidth = 1
        self.nextBtn.layer.borderColor = BODER_COLOR.CGColor
        self.nextBtn.backgroundColor = NAVIGATIONBAR_RED_COLOR
        self.nextBtn.hidden = true
        self.addBtn.layer.masksToBounds = true
        self.addBtn.layer.cornerRadius = 10
        self.addDoubleTapGesture()
    }
    
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    
    func addDoubleTapGesture() {
        let doubletap = UITapGestureRecognizer(target: self, action: #selector(self.handleDoubleTap))
        doubletap.numberOfTapsRequired = 2
        self.collection!.addGestureRecognizer(doubletap)
    }
    
    func handleDoubleTap(gestureRecognizer: UITapGestureRecognizer) {
        self.hideAllDeleteBtn()
    }
    
    func hideAllDeleteBtn() {
        if !deleteBtnFlag {
            deleteBtnFlag = true
            rotateAniFlag = true
            self.collection!.reloadData()
        }
    }

    @IBAction func lightBtnClike(sender: UIButton){
            if sender == self.light1{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light1.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light1.titleLabel?.text!)!)
                }else{
                    self.light1.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light1.titleLabel?.text)!)!)
                }
                
                
            }
            if sender == self.light2{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light2.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light2.titleLabel?.text!)!)
 
                }else{
                    self.light2.backgroundColor = UIColor.whiteColor()
                    lightArray.removeAtIndex(self.lightArray.indexOf((self.light2.titleLabel?.text)!)!)
                }
                
            }
            if sender == self.light3{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light3.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light3.titleLabel?.text!)!)

                }else{
                    self.light3.backgroundColor = UIColor.whiteColor()
                    lightArray.removeAtIndex(self.lightArray.indexOf((self.light3.titleLabel?.text)!)!)
                }
                
                
            }
            if sender == self.light4{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light4.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light4.titleLabel?.text!)!)

                }else{
                    self.light4.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light4.titleLabel?.text)!)!)
                }
                
            }
            if sender == self.light5{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light5.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light5.titleLabel?.text!)!)
                }else{
                    self.light5.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light5.titleLabel?.text)!)!)
                }
               
                
            }
            if sender == self.light6{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light6.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light6.titleLabel?.text!)!)
                }else{
                    self.light6.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light6.titleLabel?.text)!)!)
                    
                }
                
                
            }
            if sender == self.light7{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light7.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light7.titleLabel?.text!)!)
                }else{
                    self.light7.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light7.titleLabel?.text)!)!)
                }
                
                
            }
            if sender == self.light8{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light8.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light8.titleLabel?.text!)!)

                }else{
                    self.light8.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light8.titleLabel?.text)!)!)
                }
                
            }
            if sender == self.light9{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light9.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light9.titleLabel?.text!)!)
                }else{
                    self.light9.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light9.titleLabel?.text)!)!)
                }
               
                
            }
            if sender == self.light10{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light10.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light10.titleLabel?.text!)!)
                }else{
                    self.light10.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light10.titleLabel?.text)!)!)
                }
                
                
            }
            if sender == self.light11{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light11.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light11.titleLabel?.text!)!)
                }else{
                    self.light11.backgroundColor = UIColor.whiteColor()
                    lightArray.removeAtIndex(self.lightArray.indexOf((self.light11.titleLabel?.text)!)!)
                }
                
                
            }
            if sender == self.light12{
                sender.selected = !sender.selected
                if sender.selected{
                    self.light12.backgroundColor = NAVIGATIONBAR_RED_COLOR
                    lightArray.append((self.light12.titleLabel?.text!)!)
                }else{
                    self.light12.backgroundColor = UIColor.whiteColor()
                    self.lightArray.removeAtIndex(self.lightArray.indexOf((self.light12.titleLabel?.text)!)!)
                }
            }
        if sender == self.nextBtn{
            sender.selected = !sender.selected
            if sender.selected{
                self.nextBtn.backgroundColor = UIColor.whiteColor()
                self.lightArray.removeAtIndex(self.lightArray.indexOf((self.nextBtn.titleLabel?.text)!)!)
                
            }else{
                self.nextBtn.backgroundColor = NAVIGATIONBAR_RED_COLOR
                self.lightArray.append((self.nextBtn.titleLabel?.text)!)
            }
            
        }
    }
    // MARK: - Table view delegate
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.row == 4{
            self.companyName.resignFirstResponder()
            self.positionName.resignFirstResponder()
            self.nextLight.resignFirstResponder()
            
        ActionSheetDatePicker.showPickerWithTitle("开始时间", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
                
                let obj = selectedDate as! NSDate
                self.startTimePlace.alpha = 0
                self.startTime.text = publicMethod.dataFromString(obj)
                
                }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
                                    print("cancel")
                }, origin: self.view)
            
            
        }
        if indexPath.row == 5{
            self.companyName.resignFirstResponder()
            self.positionName.resignFirstResponder()
            self.nextLight.resignFirstResponder()
            
            ActionSheetDatePicker.showPickerWithTitle("结束时间", datePickerMode: UIDatePickerMode.Date, selectedDate: NSDate(), doneBlock: {(picker: ActionSheetDatePicker!, selectedDate: AnyObject!, origin: AnyObject!) -> Void in
                
                let obj = selectedDate as! NSDate
                self.endTimePlace.alpha = 0
                self.endTime.text = publicMethod.dataFromString(obj)
                
                }, cancelBlock: {(picker: ActionSheetDatePicker!) -> Void in
                    print("cancel")
                }, origin: self.view)

        }
        if indexPath.row == 6{
            self.btnPickTouch()
        }

        
    }
    @IBAction func addNextLightClicked(sender: UIButton){
        if self.nextLight.text == ""{
            SVProgressHUD.showErrorWithStatus("请输入")
            
        } else {
            if self.nextLight.text?.characters.count > 4{
               SVProgressHUD.showErrorWithStatus("请输入4字以内")
            } else {
                self.nextBtn.setTitle(self.nextLight.text, forState: UIControlState.Normal)
                self.nextBtn.titleLabel?.textColor = UIColor.lightGrayColor()
                self.nextBtn.hidden = false
                self.lightArray.append(self.nextLight.text!)

                
            }
        }
    }
    //MARK:collectionDeleagte
    //选取照片相关
    @available(iOS 8.0, *)
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithPhotosModels models: [MTImagePickerPhotosModel]) {
        self.dataSource = models
        for index in 0...self.dataSource.count - 1{
            let model = self.dataSource[index]
            self.collectionArr.append(model.getThumbImage()!)
            
            self.collectionStrArr.append(model.getFileName()!)
        }
        self.collection.hidden = false
        self.collection.dataSource = self
        self.collection.delegate = self
        self.photoBtn.hidden = true
        self.collection.reloadData()
    }
    
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithAssetsModels models: [MTImagePickerAssetsModel]) {
        self.dataSource = models
       
            self.collection.hidden = false
            self.collection.dataSource = self
            self.collection.delegate = self
            self.photoBtn.hidden = true
            self.collection.reloadData()
    }
    
    
    
    @IBAction func btnPickTouch() {
        
        var mediaTypes = [MTImagePickerMediaType]()
        let source = MTImagePickerSource.Photos
        mediaTypes.append(MTImagePickerMediaType.Photo)
        let vc = MTImagePickerController.instance
        vc.mediaTypes = mediaTypes
        vc.source = source
        vc.delegate = self
        vc.maxCount = 6
        let nc = UINavigationController(rootViewController: vc)
        self.presentViewController(nc, animated: true, completion: nil)

    }
    
    
    //MARK:UICollectionViewDataSource
    //每一组有多少个cell
    func collectionView(collectionView:UICollectionView,numberOfItemsInSection section: Int) -> Int{
        
        if self.dataSource.count == 0{
            return 0
        }else{
            return (self.dataSource.count)
        }
        
        
    }
    //设置每组的cell的边界
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,insetForSectionAtIndex section: Int) -> UIEdgeInsets{
        
        return UIEdgeInsetsMake(10, 10, 10, 10)//上左下右
    }
    //最小行间距
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 10
    }
    //最小列间距
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 10
    }
    //设定全局的Cell尺寸
    func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
        
        return CGSizeMake(SCREEN_WIDTH/3-20,50)
        
    }
    //cell上显示的信息
    func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) ->UICollectionViewCell{
        
        let cell = collection.dequeueReusableCellWithReuseIdentifier("FactoryCollCell", forIndexPath: indexPath) as! FactoryCollCell
            let model = self.dataSource[indexPath.row]
        
        if self.dataSource.count == 0{
            
        }
            cell.iv.image = model.getThumbImage()
            cell.delegate = self
        cell.indexPath = indexPath
        if deleteBtnFlag == true{
            cell.deleteBtn.hidden = true
        }else{
            cell.deleteBtn.hidden = false
        }
        if (!rotateAniFlag) {
            YTAnimation.vibrateAnimation(cell)
        }else{
            cell.layer.removeAnimationForKey("shake")
        }
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
        
       // DetailPictureView.improveImgDisplay(self.collectionStrArr,index: self.collectionArr.count - 1 )
        
    }

    //MARK:FactoryCollCellDelegate
    func deleteCellAtIndexpath(indexPath: NSIndexPath, cellView: UIView){
        self.dataSource.removeAtIndex(indexPath.row)
        collectionArr.removeAtIndex(indexPath.row)
        collectionStrArr.removeAtIndex(indexPath.row)
        if collectionArr.count == 0{
            self.photoBtn.hidden = false
            deleteBtnFlag = true
            rotateAniFlag = true
        }

        self.collection.reloadData()
    }
    func showAllDeleteBtn(type: String){
        print("showAll")
        deleteBtnFlag = false
        rotateAniFlag = false
        self.collection!.reloadData()
    }
    //MARK:提交
   func publishBtn() -> Void {
       if companyName.text == ""{
        SVProgressHUD.showErrorWithStatus("请输入企业名称")
        return
       }
       if positionName.text == ""{
        SVProgressHUD.showErrorWithStatus("请输入职位名称")
        return
       }
       if startTime.text == ""{
        SVProgressHUD.showErrorWithStatus("请输入开始时间")
        return
      }
       if endTime.text == ""{
        SVProgressHUD.showErrorWithStatus("请输入结束时间")
        return
    }
    if self.collectionArr.count == 0{
        SVProgressHUD.showErrorWithStatus("请上传形象照片")
        return
    }
    if self.lightArray.count == 0{
        SVProgressHUD.showErrorWithStatus("请选择亮点")
        return
    }
    if self.lightArray.count > 5{
        SVProgressHUD.showErrorWithStatus("最多选择5个亮点")
        return
    }
    else{
        var unitMain: String = ""
        
        for index in 0...self.lightArray.count - 1{
            
            var unitmainStr: String!
            
            if index == self.lightArray.count - 1{
                unitmainStr = self.lightArray[index]
                
            }else{
                unitmainStr = ((self.lightArray[index] ) + ",")
            }
            
            unitMain += unitmainStr
            
        }
        let param = ["id":self.id!, "lastunitname": self.companyName.text!, "lastposition":self.positionName.text!, "lastbtime": self.startTime.text!, "lastetime": self.endTime.text!,"lightspot": unitMain]
        

        DataTool.uploadLicense(self.collectionArr, uploadStyleImage: nilArr, imgsrc: self.imgsrc, type: "完善求职", param: param, completionHandler:{(newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            self.msg = newDataes
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
           
            self.navigationController?.popToRootViewControllerAnimated(true)
        })
        
     }
    
    }
}


